package fragments;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.travel.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import fragments.shopactivity.GridViewOneActivity;
import fragments.shopactivity.GridViewTwoActivity;
import fragments.shopactivity.SearchActivity;
import fragments.shopactivity.ViewPageActivity;
import fragments.shopactivity.ViewPageOtherActivity;
import fragments.shopadapter.ShopGriOneAdapter;
import fragments.shopadapter.ShopGriTwoAdapter;
import fragments.shopadapter.ShopListViewAdapter;
import shopbean.PageBean;
import shopbean.ShopBean;
import shopbean.contans.ShopURL;
import tools.BannerLayout;
import tools.MyListView;
import tools.Okhttputils;

/**
 * 商城模块
 * Created by Administrator on 2016/10/17.
 */
public class ShopFragment extends Fragment {
    BannerLayout homeVp;
    @Bind(R.id.shop_gvOne)
    GridView shopGvOne;
    @Bind(R.id.shop_gvTwo)
    GridView shopGvTwo;
    @Bind(R.id.Lv)
    MyListView Lv;
    @Bind(R.id.llTwo)
    LinearLayout llTwo;
    @Bind(R.id.llOne)
    LinearLayout llOne;
    @Bind(R.id.shop_search_iv)
    ImageView shopSearchIv;
    private PullToRefreshScrollView shopRefresh;
    private ImageView imageAnim;
    private View mView;
    private List<String> mList = new ArrayList<>();//存放imageUrl的集合
    private List<ShopBean.DataBean.IndexAdListBean> mIndexList = new ArrayList<>();
    private ShopGriOneAdapter mShopAdapterOne;//商城模块的第一个GridView的Adapter
    private List<ShopBean.DataBean.TypeListBean> mtypeList = new ArrayList<>();
    private ShopGriTwoAdapter mShopAdapterTwo;//商城模块的第二个GridView的Adapter
    private List<ShopBean.DataBean.AdListBean> mAdlList = new ArrayList<>();
    private ShopListViewAdapter mShopListViewAdapter;//商城模块的热卖商品部分
    private List<PageBean.DataBean.LineBean> mLinelist = new ArrayList<>();
    private AnimationDrawable drawable;
    //分页
    int pageindex = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //viewpager轮播图
                    mIndexList = (List<ShopBean.DataBean.IndexAdListBean>) msg.obj;
                    for (int i = 0; i < mIndexList.size(); i++) {
                        mList.add(mIndexList.get(i).getPic());
                    }
                    homeVp.setViewUrls(mList);
                    drawable.stop();
                    imageAnim.setVisibility(View.GONE);
                    homeVp.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            if (mIndexList.get(position).getType().trim().equals("activity")) {
                                Intent intent = new Intent(getActivity(), ViewPageActivity.class);
                                intent.putExtra("title", mIndexList.get(position).getTitle());
                                intent.putExtra("url", mIndexList.get(position).getUrl());
                                intent.putExtra("pic", mIndexList.get(position).getPic());
                                startActivity(intent);
                            } else {
                                Intent intent1 = new Intent(getActivity(), ViewPageOtherActivity.class);
                                intent1.putExtra("url", mIndexList.get(position).getUrl());
                                startActivity(intent1);
                            }
                        }
                    });
                    break;
                case 2:// 加载第一个GridView数据
                    mtypeList = (List<ShopBean.DataBean.TypeListBean>) msg.obj;
                    mShopAdapterOne = new ShopGriOneAdapter(getContext(), mtypeList);
                    shopGvOne.setAdapter(mShopAdapterOne);
                    shopGvOne.setVisibility(View.VISIBLE);
                    drawable.stop();
                    imageAnim.setVisibility(View.GONE);
                    shopGvOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(getActivity(), GridViewOneActivity.class);
                            startActivity(intent);
                        }
                    });
                    break;
                case 3:// 加载第二个GridView数据
                    mAdlList = (List<ShopBean.DataBean.AdListBean>) msg.obj;
                    mShopAdapterTwo = new ShopGriTwoAdapter(getContext(), mAdlList);
                    shopGvTwo.setAdapter(mShopAdapterTwo);
                    drawable.stop();
                    imageAnim.setVisibility(View.GONE);
                    llOne.setVisibility(View.VISIBLE);
                    shopGvTwo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(getActivity(), GridViewTwoActivity.class);
                            intent.putExtra("url", mAdlList.get(i).getUrl());
                            intent.putExtra("pic", mAdlList.get(i).getPic());
                            startActivity(intent);
                        }
                    });
                    break;
                case 4://商城模块的热卖商品部分
                    if (pageindex == 1) {
                        mLinelist = (List<PageBean.DataBean.LineBean>) msg.obj;
                        mShopListViewAdapter = new ShopListViewAdapter(getContext(), mLinelist);
                        Lv.setAdapter(mShopListViewAdapter);
                        shopRefresh.onRefreshComplete();
                        drawable.stop();
                        imageAnim.setVisibility(View.GONE);
                        llTwo.setVisibility(View.VISIBLE);
                    } else {
                        mLinelist.addAll((List<PageBean.DataBean.LineBean>) msg.obj);
                        mShopListViewAdapter.notifyDataSetChanged();
                        shopRefresh.onRefreshComplete();
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_shop, container, false);
        shopRefresh = (PullToRefreshScrollView) mView.findViewById(R.id.shop_refresh);
        shopRefresh.setMode(PullToRefreshBase.Mode.BOTH);//设置可上拉刷新和下拉刷新

        ButterKnife.bind(this, mView);
        homeVp = (BannerLayout) mView.findViewById(R.id.home_vp);
        imageAnim = (ImageView) mView.findViewById(R.id.image_anim);
        drawable = (AnimationDrawable) imageAnim.getBackground();
        imageAnim.setVisibility(View.VISIBLE);
        drawable.start();
        initViewP();//加载ViewPage的轮播图
        homeVp.requestFocus();
        homeVp.setFocusable(true);
        homeVp.setFocusableInTouchMode(true);
        shopSearchIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });
        initDataGvone();// 加载第一个GridView数据
        initDataGvTwo();// 加载第二个GridView数据
        initDataList();//商城模块的热卖商品部分
        initFresh();//下拉刷新加载数据
        return mView;
    }

    private void initFresh() {
        shopRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                pageindex = 1;
                initDataList();
//                shopRefresh.onRefreshComplete();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                pageindex++;
                initDataList();
//                shopRefresh.onRefreshComplete();
            }
        });
    }

    private void initDataList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    /*
                    /*
                    {
    "code": 0,                          {
    "code": 0,
    "msg": "success",
    "data": {
        "total": "689",
        "nextPage": "3",
        "line": []
    }
}
    "msg": "success",
    "data": {
        "typeList": [],
        "adList": [],
        "indexAdList": [],
        "list": {}
    }
}                    */
                    String jsonString = Okhttputils.getInstance().run(ShopURL.URLHEADP + pageindex + ShopURL.URLFOOTP);
                    JSONObject data = JSONObject.parseObject(jsonString).getJSONObject("data");
                    //JSONObject list = data.getJSONObject("list");
                    // String line = list.getString("line");
                    String line = data.getString("line");
                    List<PageBean.DataBean.LineBean> lineBean = new ArrayList<>();
                    lineBean = JSONArray.parseArray(line, PageBean.DataBean.LineBean.class);
//                    Log.i("TAG", "list------>" + lineBean.size());
                    Message message = new Message();
                    message.what = 4;
                    message.obj = lineBean;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initDataGvTwo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = Okhttputils.getInstance().run(ShopURL.URLHEAD + pageindex + ShopURL.URLFOOT);
//                    Log.i("TAG", "json------>" + jsonString);
                    JSONObject obj = JSONObject.parseObject(jsonString).getJSONObject("data");
                    String adList = obj.getString("adList");
                    List<ShopBean.DataBean.AdListBean> adl = new ArrayList<ShopBean.DataBean.AdListBean>();
                    adl = JSONArray.parseArray(adList, ShopBean.DataBean.AdListBean.class);
                    Message message = new Message();
                    message.what = 3;
                    message.obj = adl;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initDataGvone() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = Okhttputils.getInstance().run(ShopURL.URLHEAD + pageindex + ShopURL.URLFOOT);
//                    Log.i("TAG","json------>"+jsonString);
                    JSONObject obj = JSON.parseObject(jsonString).getJSONObject("data");
                    String typeList = obj.getString("typeList");
                    List<ShopBean.DataBean.TypeListBean> typeListBeen = new ArrayList<ShopBean.DataBean.TypeListBean>();
                    typeListBeen = JSONArray.parseArray(typeList, ShopBean.DataBean.TypeListBean.class);
//                    Log.i("TAG","list------>"+typeListBeen.size());
                    Message message = new Message();
                    message.what = 2;
                    message.obj = typeListBeen;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //加载ViewPage的轮播图
    private void initViewP() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = Okhttputils.getInstance().run(ShopURL.URLHEAD + pageindex + ShopURL.URLFOOT);
//                    Log.i("TAG","json------>"+jsonString);
                    JSONObject obj = JSONObject.parseObject(jsonString).getJSONObject("data");
                    String indexAdList = obj.getString("indexAdList");
                    List<ShopBean.DataBean.IndexAdListBean> list = new ArrayList<ShopBean.DataBean.IndexAdListBean>();
                    list = JSONArray.parseArray(indexAdList, ShopBean.DataBean.IndexAdListBean.class);
//                    Log.i("TAG","list------>"+list.size());
                    Message message = new Message();
                    message.obj = list;
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
